package com.znufe.exam.controller.admin;

import java.util.Date;

import com.github.pagehelper.PageInfo;
import com.znufe.exam.base.BaseApiController;


import com.znufe.exam.configuration.config.annotation.Log;
import com.znufe.exam.configuration.config.enums.BusinessType;
import com.znufe.exam.utility.PageInfoHelper;
import com.znufe.exam.viewmodel.admin.lecturer.LectureCreateVM;
import com.znufe.exam.viewmodel.admin.lecturer.LecturerPageRequestVM;
import com.znufe.exam.viewmodel.admin.lecturer.LecturerResponseVM;

import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.znufe.exam.domain.Lecturer;
import com.znufe.exam.service.LecturerService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import com.znufe.exam.base.RestResponse;
import com.znufe.exam.base.SystemCode;

import javax.validation.Valid;

/**   
 * 
 * @Description:  讲师表接口层
 * @Author:       gong   
 * @CreateDate:   Lecturer
 * @Version:      V1.0
 *    
 */
@Api(description = "讲师表",value="讲师表" )
@RestController("AdminLecturerController")
@RequestMapping(value="api/admin/lecturer")
@AllArgsConstructor
public class LecturerController extends BaseApiController {

	private final LecturerService lecturerService;

	/**
	 * edit
	 *
	 * @return: com.znufe.exam.base.RestResponse<Lecturer>
	 * @param: [model]
	 * @Author: lin keqing
	 */
	@PreAuthorize("@ss.hasAnyPermi('courses:lecturer:add,courses:lecturer:update')")
    @Log(title = "讲师管理", businessType = BusinessType.EDIT)
	@RequestMapping(value="/edit", method = RequestMethod.POST)
	@ApiOperation(value = "讲师信息的编辑接口（新增/更新）",
			      notes = "新增/更新某个讲师的信息[lecturer](更新请传入讲师id)，作者：lin keqing")
    public RestResponse<Lecturer> edit(@RequestBody @Valid LectureCreateVM model) {
        if (model.getId() == null) {
            // 若请求体中没有id，判断新增信息中是否已经存在
            Lecturer existLecture = lecturerService.
                        getLecturerByName(model.getLecturerName());

            if (null != existLecture) {
                return new RestResponse<>(2, "讲师已存在");
            }
        }

        Lecturer lecturer = modelMapper.map(model, Lecturer.class);
        if (model.getId() == null) {
            lecturer.setGmtCreate(new Date());
            lecturer.setStatus(0);
            lecturer.setIsDeleted(0);
            lecturerService.insertByFilter(lecturer);
        } else {
            lecturer.setGmtModified(new Date());
            lecturerService.updateByIdFilter(lecturer);
        }
        return RestResponse.ok(lecturer);
    }

    /**
     * delete
     *
     * @return: com.znufe.exam.base.RestResponse
     * @param: [id]
     * @Author: lin keqing
     */
    @PreAuthorize("@ss.hasPermi('courses:lecturer:delete')")
    @Log(title = "讲师管理", businessType = BusinessType.DELETE)
	@RequestMapping(value="/delete/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "讲师信息的删除接口（通过讲师的id号删除）", notes = "删除某个讲师的信息[lecturer]，作者：lin keqing")
	public RestResponse delete(@PathVariable Integer id) {
		Lecturer lecturer = lecturerService.selectByPrimaryKey(id);
		lecturer.setIsDeleted(1);
		System.out.println(lecturer.toString());
		lecturerService.updateByIdFilter(lecturer);
		return RestResponse.ok();
	}

    @PreAuthorize("@ss.hasPermi('courses:lecturer:update')")
    @Log(title = "讲师管理", businessType = BusinessType.UPDATE)
	@RequestMapping(value="/changeStatus/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "改变某个讲师的启用状态接口（启用/禁用）", notes = "改变某个讲师的启用状态[lecturer]，作者：lin keqing")
	public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
		Lecturer lecturer = lecturerService.selectByPrimaryKey(id);
		Integer newStatus = lecturer.getStatus() == 0 ? 1 : 0;
		lecturer.setStatus(newStatus);
		lecturer.setGmtModified(new Date());
		lecturerService.updateByIdFilter(lecturer);
		return RestResponse.ok(newStatus);
	}

    @PreAuthorize("@ss.hasPermi('courses:lecturer:query')")
	@RequestMapping(value = "/select/{id}", method = RequestMethod.POST, produces = "application/json")
	@ApiOperation(value = "根据id查找讲师(编辑按钮调用这个接口)",notes = "返回部分讲师信息")
	@ApiImplicitParam(paramType="path", name = "id", value = "讲师id", dataType = "int",required = true)
	public RestResponse<LectureCreateVM> select(@PathVariable Integer id) {
		Lecturer lecturer = lecturerService.selectByPrimaryKey(id);
		LectureCreateVM vm = modelMapper.map(lecturer, LectureCreateVM.class);
		return RestResponse.ok(vm);
	}

	/**
	 * pageList
	 *
	 * @return: RestResponse<PageInfo<LecturerResponseVM>>
	 * @param: [model]
	 * @Author: lin keqing
	 */
    @PreAuthorize("@ss.hasPermi('courses:lecturer:list')")
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	@ApiOperation(value = "讲师信息的页面查询接口（无参数查找/按讲师名字查找/按讲师职称查找）",
			      notes = "查询讲师信息[lecturer]（按职称查找请传入职称对应的id号），作者：lin keqing")
	public RestResponse<PageInfo<LecturerResponseVM>> pageList(@RequestBody LecturerPageRequestVM model) {
		model = LecturerPageRequestVM.wipeBlank(model);
		PageInfo<Lecturer> pageInfo = lecturerService.page(model);
		PageInfo<LecturerResponseVM> page = PageInfoHelper.copyMap(pageInfo,
				d -> LecturerResponseVM.from(d));
		return RestResponse.ok(page);
	}
}